<template>
  <div>
    <!-- 标题和箭头 -->
    <div class="flex items-center justify-between mb-3 mt-4">
      <!-- 左侧：标题 -->
      <div class="flex items-center">
        <div class="text-lg inline-block mr-2 cursor-pointer" @click="handleGoList(item)">
          {{ isZh ? item.name : item.nameEn }}
        </div>
        <van-icon name="arrow" @click="handleGoList(item)" class="cursor-pointer" />
      </div>

      <!-- 右侧：左右箭头（桌面端显示） -->
      <div class="hidden md:flex items-center gap-2">
        <!-- 左箭头 -->
        <button
          class="nav-arrow"
          :class="{ 'nav-arrow-disabled': !canScrollLeft }"
          :disabled="!canScrollLeft"
          @click="scrollLeft"
          aria-label="向左滚动">
          <van-icon name="arrow-left" size="14" :color="canScrollLeft ? '#333' : '#ccc'" />
        </button>

        <!-- 右箭头 -->
        <button
          class="nav-arrow"
          :class="{ 'nav-arrow-disabled': !canScrollRight }"
          :disabled="!canScrollRight"
          @click="scrollRight"
          aria-label="向右滚动">
          <van-icon name="arrow" size="14" :color="canScrollRight ? '#333' : '#ccc'" />
        </button>
      </div>
    </div>

    <!-- 响应式横向滚动容器 -->
    <div class="scroll-wrapper">
      <!-- 滚动容器 -->
      <div ref="scrollContainer" class="scroll-container overflow-x-auto scrollbar-hide" @scroll="handleScroll">
        <div class="scroll-content flex gap-4">
          <div
            v-for="item in items"
            :key="item.id"
            class="scroll-item flex-shrink-0 cursor-pointer relative"
            :style="{ width: itemWidth }"
            @click="handleClick(item)">
            <!-- 图片 -->
            <img :src="imageBaseUrl + item.picUrl" class="rounded-lg w-full aspect-square object-cover" alt="" />

            <!-- 标题 -->
            <div class="flex items-center justify-between mt-2 mb-1">
              <h3 class="text-sm font-semibold text-gray-800 truncate pr-2">
                {{ $store.getters.isZh ? item.name : item.nameEn }}
              </h3>
            </div>

            <!-- 收藏图标 -->
            <van-icon
              class="absolute top-2 right-2"
              :name="item.favorite ? 'like' : 'like-o'"
              :color="item.favorite ? '#ff7a00' : '#999'"
              size="28"
              @click.stop="handleFavorite(item)" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { addFavorite, removeFavorite } from "@/apis/favorite"

export default {
  props: {
    item: { type: Object, required: true },
    items: { type: Array, required: true },
    isZh: { type: Boolean, required: true },
  },

  data() {
    return {
      containerWidth: 0, // 容器宽度
      itemsPerView: 2, // 每屏显示的项目数量
      canScrollLeft: false, // 是否可以向左滚动
      canScrollRight: false, // 是否可以向右滚动
      scrollPosition: 0, // 当前滚动位置
      resizeTimer: null, // 窗口调整防抖定时器
    }
  },

  computed: {
    imageBaseUrl() {
      return process.env.VUE_APP_IMAGE_URL
    },

    // 计算每个项目的宽度
    itemWidth() {
      if (this.containerWidth === 0) return "50%"

      const gap = 16 // gap-4 = 16px

      // 判断是否为移动端
      const isMobile = this.containerWidth < 640

      if (isMobile) {
        // 移动端：让每个项目略小于可见宽度的一半，这样能看到半个下一项
        // 例如：可见宽度 375px，每项约 180px，可以看到下一项的一部分
        const visibleWidth = this.containerWidth
        const itemWidth = (visibleWidth - gap * 1.5) / 2.3 // 2.3 是为了露出半个
        return `${itemWidth}px`
      } else {
        // 桌面端：完整显示
        const totalGaps = (this.itemsPerView - 1) * gap
        const itemWidth = (this.containerWidth - totalGaps) / this.itemsPerView
        return `${itemWidth}px`
      }
    },
  },

  mounted() {
    // 初始计算
    this.$nextTick(() => {
      this.calculateLayout()
      this.updateArrowsVisibility()
    })

    // 监听窗口大小变化（加大防抖时间，因为用户很少调整窗口）
    window.addEventListener("resize", this.handleResize)
  },

  beforeDestroy() {
    window.removeEventListener("resize", this.handleResize)
    // 清理防抖定时器
    if (this.resizeTimer) {
      clearTimeout(this.resizeTimer)
    }
  },

  methods: {
    // 计算布局参数
    calculateLayout() {
      if (!this.$refs.scrollContainer) return

      const container = this.$refs.scrollContainer
      this.containerWidth = container.offsetWidth

      // 根据容器宽度确定每屏显示的项目数量
      // 断点参考：
      // < 640px (mobile): 2项
      // 640-768px (sm): 3项
      // 768-1024px (md): 4项
      // 1024-1280px (lg): 5项
      // >= 1280px (xl): 6项

      if (this.containerWidth < 640) {
        this.itemsPerView = 2
      } else if (this.containerWidth < 768) {
        this.itemsPerView = 4
      } else if (this.containerWidth < 1024) {
        this.itemsPerView = 5
      } else if (this.containerWidth < 1280) {
        this.itemsPerView = 6
      } else {
        this.itemsPerView = 7
      }

      // const isMobile = this.containerWidth < 640
      // console.log("📊 [ScrollGrid布局] 容器宽度:", this.containerWidth, "px | 每屏显示:", this.itemsPerView, "项 | 移动端:", isMobile)
    },

    // 处理窗口大小变化（加大防抖，因为用户很少调整窗口）
    handleResize() {
      // 清除之前的定时器
      if (this.resizeTimer) {
        clearTimeout(this.resizeTimer)
      }

      // 300ms 防抖（用户调整窗口不频繁，可以延迟更新）
      this.resizeTimer = setTimeout(() => {
        this.calculateLayout()
        this.updateArrowsVisibility()
      }, 300)
    },

    // 处理滚动事件 - 更新箭头显示状态
    handleScroll() {
      this.updateArrowsVisibility()
    },

    // 更新箭头可用状态
    updateArrowsVisibility() {
      if (!this.$refs.scrollContainer) {
        this.canScrollLeft = false
        this.canScrollRight = false
        return
      }

      const container = this.$refs.scrollContainer
      const scrollLeft = container.scrollLeft
      const scrollWidth = container.scrollWidth
      const clientWidth = container.clientWidth

      // 更新滚动位置
      this.scrollPosition = scrollLeft

      // 判断是否可以向左滚动（滚动位置 > 5px）
      this.canScrollLeft = scrollLeft > 5

      // 判断是否可以向右滚动（未滚动到底部）
      this.canScrollRight = scrollLeft < scrollWidth - clientWidth - 5

      // console.log("📜 [箭头状态] 左:", this.canScrollLeft, "| 右:", this.canScrollRight, "| 位置:", scrollLeft.toFixed(0))
    },

    // 向左滚动
    scrollLeft() {
      if (!this.$refs.scrollContainer) return

      const container = this.$refs.scrollContainer
      const gap = 16 // gap-4 = 16px
      const itemWidth = (this.containerWidth - (this.itemsPerView - 1) * gap) / this.itemsPerView

      // 每次滚动一屏的距离
      const scrollDistance = itemWidth * this.itemsPerView + gap * (this.itemsPerView - 1)

      container.scrollBy({
        left: -scrollDistance,
        behavior: "smooth",
      })

      // console.log("⬅️ [向左滚动] 距离:", scrollDistance.toFixed(0), "px")
    },

    // 向右滚动
    scrollRight() {
      if (!this.$refs.scrollContainer) return

      const container = this.$refs.scrollContainer
      const gap = 16 // gap-4 = 16px
      const itemWidth = (this.containerWidth - (this.itemsPerView - 1) * gap) / this.itemsPerView

      // 每次滚动一屏的距离
      const scrollDistance = itemWidth * this.itemsPerView + gap * (this.itemsPerView - 1)

      container.scrollBy({
        left: scrollDistance,
        behavior: "smooth",
      })

      // console.log("➡️ [向右滚动] 距离:", scrollDistance.toFixed(0), "px")
    },

    // 处理收藏
    async handleFavorite(item) {
      try {
        if (item.favorite) {
          await removeFavorite({ spuId: item.id })
          this.$emit("updateFavorite", item.id, false)
        } else {
          await addFavorite({ spuId: item.id })
          this.$emit("updateFavorite", item.id, true)
        }
      } catch (error) {
        console.log("收藏操作失败 :>> ", error)
      }
    },

    // 点击项目
    handleClick(item) {
      this.$router.push({
        name: "productDetail",
        query: { id: item.id, type: item.type, favorite: item.favorite },
      })
    },

    // 查看更多
    handleGoList(item) {
      this.$router.push({
        name: "productsList",
        query: { id: item.id },
      })
    },
  },
}
</script>

<style scoped>
/* 隐藏滚动条 */
.scrollbar-hide {
  -ms-overflow-style: none; /* IE 和 Edge */
  scrollbar-width: none; /* Firefox */
}

.scrollbar-hide::-webkit-scrollbar {
  display: none; /* Chrome, Safari, Opera */
}

/* 滚动容器包装器 */
.scroll-wrapper {
  position: relative;
}

/* 滚动容器 */
.scroll-container {
  position: relative;
  scroll-behavior: smooth;
  -webkit-overflow-scrolling: touch; /* iOS 平滑滚动 */
}

/* 桌面端：使用 scroll-snap */
@media (min-width: 768px) {
  .scroll-container {
    scroll-snap-type: x mandatory;
  }

  .scroll-item {
    scroll-snap-align: start;
  }
}

/* 图片加载优化 */
.scroll-item img {
  will-change: transform;
}

/* 收藏图标悬停效果 */
.scroll-item .van-icon {
  transition: transform 0.2s ease;
}

.scroll-item .van-icon:hover {
  transform: scale(1.1);
}

/* 导航箭头按钮 */
.nav-arrow {
  width: 22px;
  height: 22px;
  border-radius: 50%;
  background: #ffffff;
  border: 1px solid #e5e5e5;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
  outline: none;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}

.nav-arrow:hover:not(:disabled) {
  background: #f7f7f7;
  border-color: #d0d0d0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
}

.nav-arrow:active:not(:disabled) {
  transform: scale(0.95);
}

/* 禁用状态 */
.nav-arrow-disabled {
  cursor: not-allowed;
  background: #f5f5f5;
  border-color: #e5e5e5;
  opacity: 0.5;
}

.nav-arrow-disabled:hover {
  background: #f5f5f5;
  border-color: #e5e5e5;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}
</style>
